package com.ias.redis.serializer;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ias.redis.config.RedisProperties;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis序列化器工厂
 *
 * @author IAS Team
 * @version 2.0.0
 */
public class SerializerFactory {

    /**
     * 创建Key序列化器
     */
    public static RedisSerializer<String> createKeySerializer() {
        return new StringRedisSerializer();
    }

    /**
     * 创建Value序列化器
     */
    public static RedisSerializer<Object> createValueSerializer(RedisProperties.SerializationType type) {
        switch (type) {
            case JACKSON:
                return createJacksonSerializer();
            case JDK:
                return new JdkSerializationRedisSerializer();
            case PROTOSTUFF:
                // 可以扩展支持Protostuff
                throw new UnsupportedOperationException("Protostuff serialization not implemented yet");
            default:
                return createJacksonSerializer();
        }
    }

    /**
     * 创建Jackson序列化器
     */
    private static GenericJackson2JsonRedisSerializer createJacksonSerializer() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 注册Java 8时间模块
        objectMapper.registerModule(new JavaTimeModule());
        
        // 禁用时间戳写入
        objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        
        // 配置类型信息
        objectMapper.activateDefaultTyping(
            objectMapper.getPolymorphicTypeValidator(),
            ObjectMapper.DefaultTyping.NON_FINAL,
            JsonTypeInfo.As.PROPERTY
        );
        
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }

    /**
     * 创建压缩序列化器
     */
    public static RedisSerializer<Object> createCompressedSerializer(
            RedisSerializer<Object> delegate, 
            int threshold) {
        return new CompressedRedisSerializer(delegate, threshold);
    }
} 